package conchmusic.conchmusicclient.mainUi;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.activity.PlayActivity;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.dao.OperateDB;
import conchmusic.conchmusicclient.pojo.Artist;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.util.Invoker;
import conchmusic.conchmusicclient.util.JsonParser;
import conchmusic.conchmusicclient.util.RecoCommand;

/**
 * @author sunzehua
 */

public class RecognizeActivity extends AppCompatActivity {

    private Button record;
    private Button stop;
    private TextView show;
    private Handler handler;
    private int bufferSizeInBytes = 0;//缓冲区大小
    //音频获取来源
    private int audioSource = MediaRecorder.AudioSource.MIC;
    //设置音频的采样率，44100是目前的标准，但是某些设备仍然支持22050,16000,11025
    private static int sampleRateInHz = 44100;
    //设置音频的录制声道，CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
    private static int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    //设置音频数据格式:PCM 16位每个样本，保证设备支持。PCM 8位每个样本，不一定能得到设备的支持。
    private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;//8位不支持
    private AudioRecord audioRecord;
    private boolean isRecord = false;//设置录制状态

    private static final String AudioName = Environment.getExternalStorageDirectory()+"/first.raw";
    private static final String newAudioName= Environment.getExternalStorageDirectory()+"/Files/second.raw";

    private Thread thread;
    private Invoker invoker=new Invoker();

    //private RecoCommand reconCommand=new RecoCommand(getResources(),newAudioName);
    private RecoCommand reconCommand;
    private JsonParser jsonParser=new JsonParser();

    private MyDBHelp help=new MyDBHelp(this,"demon",null,1);
    private OperateDB db=new OperateDB(help);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recognize);
        init();
    }
    private void init() {
        record = (Button) findViewById(R.id.record);
        stop = (Button) findViewById(R.id.stop);
        show = (TextView) findViewById(R.id.show);
        bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
//        Log.i("robin", "......" + bufferSizeInBytes);
        if (audioRecord == null) {
//            Log.i("robin", "......" + "in");
            audioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes);//自己设置缓冲区大小会报audioRecord初始化失败的错误
        }
//        Log.i("robin", "......" + audioRecord);
        record.setOnClickListener(new AudioRecordLinstener());
        stop.setOnClickListener(new AudioRecordLinstener());

        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String message=(String)msg.getData().get("msgType");
                Toast.makeText(getApplicationContext(),message, Toast.LENGTH_SHORT);

            }
        };

    }
    class AudioRecordLinstener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v == record) {
                startAudioRecord();
            }
            if (v == stop) {
                stopAudioRecord();
            }

        }
    }
    /**
     * 开始录制音频
     */
    private void startAudioRecord() {
//        Log.i("robin", "......" + "in2");
        if (ContextCompat.checkSelfPermission(RecognizeActivity.this,
                Manifest.permission.RECORD_AUDIO)
                == PackageManager.PERMISSION_GRANTED) {
            Log.i("robin", "......" + "权限已授予");
        } else {
            Log.i("robin", "......" + "权限未授予");
        }
        audioRecord.startRecording();//开始录制
        isRecord = true;

//        new AudioRecordThread().start();//开启线程来把录制的音频数据保留下来
        thread=new AudioRecordThread();
        thread.start();
    }
    /**
     * 停止录制音频
     */
    private void stopAudioRecord() {

        close();
    }

    private void close() {
        if (audioRecord != null) {
            System.out.println("stopRecord");
            isRecord = false;//停止文件写入
            audioRecord.stop();
            try {
                thread.join();
                Log.i("recoactivity157","...................");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            audioRecord.release();//释放资源
//            audioRecord = null;
            new Thread(){
                @Override
                public void run() {
               super.run();
//                    try {
//                        Thread.sleep(10000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    invoker.setTransferCommand(reconCommand);
                    reconCommand = new RecoCommand(getResources(),newAudioName);
                    invoker.setTransferCommand(reconCommand);
                    String type=invoker.action();
                    Log.i("panke",type+".......");
                    String content= null;
                    try {
                        content = jsonParser.typeOf(type);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if("songs".equals(content)){
                        List<Song> list=new ArrayList<Song>();
                        try {
                            list=jsonParser.parseSongs(type);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        List<Integer>  list1=new ArrayList<Integer>();
                        Intent intent = new Intent();
                        intent.setClass(RecognizeActivity.this, PlayActivity.class);
                        for(Song s:list){
                            operateSong(s,null);
                            list1.add(s.getSongId());
                        }
                        intent.putIntegerArrayListExtra("key", (ArrayList<Integer>) list1);
                        startActivity(intent);
                    }else{
                        Bundle bundle=new Bundle();
                        try {
                            bundle.putString("msgType",jsonParser.parseInvalidInfo(type));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Message message=new Message();
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }.start();
        }
    }

    /**
     * 音频数据写入线程
     *
     *
     */
    class AudioRecordThread extends Thread {
        @Override
        public void run() {
            super.run();
            writeData();

            //把录制的音频裸数据写入到文件中去
        }
    }
    private void writeData() {
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        byte[] buffer = new byte[(int) 1024];
//
//                while (isRecord) {
//            int count = audioRecord.read(buffer, 0, buffer.length);
//            if (count > 0) {
//                try {
//                    out.write(buffer, 0, count);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//        }
//
//
//        byte[] b = out.toByteArray();           //打印输出字节流的方法
//        try {
//            out.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        for (int i = 0; i < b.length; i++) {
//            System.out.println(b[i]);
//        }
//    }

        int readSize = 0;
        byte[] buffer = new byte[(int) 1024];
        FileOutputStream fos = null;
        File file = new File(AudioName);
        if (file.exists())
            file.delete();
        try {
            fos = new FileOutputStream(file);//获取一个文件的输出流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (isRecord == true) {
            readSize = audioRecord.read(buffer, 0, buffer.length);
            if (AudioRecord.ERROR_INVALID_OPERATION != readSize) {
                try {
                    fos.write(buffer, 0, readSize);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        copyWaveFile();
    }
    public void copyWaveFile() {

        byte[] buffer = new byte[(int) 1024];
        FileOutputStream fos = null;
        File file1 = new File(newAudioName);
        if (file1.exists())
            file1.delete();
        try {
            fos = new FileOutputStream(file1);//获取一个文件的输出流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        File file = new File(AudioName);
        if (!file.exists()) {
            return;
        }

        try {
            int dateLength = (int) (file.length() / 2);
            short data;
            byte Bytedata;

            InputStream is = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);

            int size=0;
            int i = 0;
            while (dis.available() > 0) {
                data = dis.readShort();
                // 16位转8位 保留前八位 第一位取反
                if (data > 0x8000) {
                    Bytedata = (byte) (0x80 - (0xff - data >> 8));
                } else {
                    Bytedata = (byte) (0x80 + (data>> 8));
                }
                out.write(Bytedata);
                fos.write(Bytedata);
                i++;
            }

//                byte[] b=out.toByteArray();
//                for(int j=0;j<b.length;j++){
//                    System.out.println(b[j]);
//
//                }
//                out.write(Bytedata);
            dis.close();
            out.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        invoker.setTransferCommand(reconCommand);
    }

    private void operateSong(Song song,String tip){
        int localSongId=db.findLocalSongId(song.getTitle(),song.getAlbumName());
        if(localSongId!=0){
            song.setLocalSongId(localSongId);
            db.updateSong(song);
//            if(!db.findSong_SongList(1,localSongId)) {
//                db.addSong_SongList(1,localSongId);
//            }
//            if(tip.equals("down")){
//                if(!db.findSong_SongList(2,localSongId)){
//                    db.addSong_SongList(2,localSongId);
//                }
//            }
        } else{
            db.addSong(song);
            int localSongId2=db.findLocalSongId(song.getTitle(),song.getAlbumName());
            for(int j=0;j<song.getArtistNames().size();j++) {
                Artist artist=new Artist(0,song.getArtistIds().get(j),song.getArtistNames().get(j),"",null,null);
                if(db.findArtist(artist.getArtistName())!=0){
                    db.updateArtist(artist);
                }else {
                    db.addArtist(artist);
                }
                if(!db.findArtist_Song(db.findArtist(artist.getArtistName()),localSongId2))
                {
                    db.addArtist_Song(db.findArtist(artist.getArtistName()),localSongId2);
                }
            }
//            if(!db.findSong_SongList(1,localSongId2)) {
//                db.addSong_SongList(1,localSongId2);
//            }
//            if(tip.equals("down")){
//                if(!db.findSong_SongList(2,localSongId2)){
//                    db.addSong_SongList(2,localSongId2);
//                }
//            }
        }
    }
}
//        while (isRecord) {
//            int count = audioRecord.read(buffer, 0, buffer.length);
//            if (count > 0) {
//                try {
//                    out.write(buffer, 0, count);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//        }
//
//
//        byte[] b = out.toByteArray();           //打印输出字节流的方法
//        try {
//            out.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        for (int i = 0; i < b.length; i++) {
//            System.out.println(b[i]);
//        }
//    }



//        // new一个byte数组用来存一些字节数据，大小为缓冲区大小
//        byte[] audioData = new byte[bufferSizeInBytes];
//        int readSize = 0;
//        FileOutputStream fos = null;
//        File file = new File(AudioName);
//        if(file.exists())
//            file.delete();
//        try
//        {
//            fos = new FileOutputStream(file);//获取一个文件的输出流
//        } catch (FileNotFoundException e)
//        {
//            e.printStackTrace();
//        }
//
//        while(isRecord == true)
//        {
//            readSize = audioRecord.read(audioData, 0, bufferSizeInBytes);
////            Log.d(TAG, "readSize ="+readSize);
//            if(AudioRecord.ERROR_INVALID_OPERATION != readSize)
//            {
//                try
//                {
//                    fos.write(audioData);
//                } catch (IOException e)
//                {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        try
//        {
//            fos.close();
//        } catch (IOException e)
//        {
//            e.printStackTrace();
//        }


